import echarts from './charts'
import { nextTick, onMounted, onUnmounted, unref, Ref } from 'vue'

/**
 * @param el 渲染节点
 * @param autoChartSize 自动重新渲染图表适应高度
 * @param animation
 * @param theme 渲染主题
 */
export default function useCharts(
  elRef,
  autoChartSize = false,
  animation = false,
  theme
) {
  // echart实例
  let echartInstance = null

  // 初始化echarts
  const initChart = () => {
    const el = unref(elRef)
    if (!el || !unref(el)) {
      return
    }
    echartInstance = echarts.init(el, theme)
  }

  //  设置配置
  const setOption = option => {
    nextTick(() => {
      if (!echartInstance) {
        initChart()
        if (!echartInstance) return
      }
      option && echartInstance.setOption(option)
    })
  }

  // 获取echart实例
  const getInstance = () => {
    if (!echartInstance) {
      initChart()
    }
    return echartInstance
  }

  // 更新大小
  const resize = () => {
    echartInstance?.resize()
  }

  // 监听元素大小
  function watchEl() {
    // 给元素添加过渡
    if (animation) {
      elRef.value.style.transition = 'width 1s, height 1s'
    }
    // eslint-disable-next-line
    const resizeObserver = new ResizeObserver(entries => resize())
    resizeObserver.observe(elRef.value)
  }

  // 显示加载
  const showLoading = () => {
    if (!echartInstance) {
      initChart()
    }
    echartInstance?.showLoading()
  }
  // 隐藏加载
  const hideLoading = () => {
    if (!echartInstance) {
      initChart()
    }
    echartInstance?.hideLoading()
  }

  const removeInstance = () => {
    if (echartInstance) {
      echartInstance = null
    }
  }

  onMounted(() => {
    window.addEventListener('resize', resize)
    if (autoChartSize) watchEl()
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resize)
  })

  return {
    setOption,
    getInstance,
    showLoading,
    hideLoading,
    removeInstance
  }
}
